#include "scrollingmessagedisplaywidget.h"
#include <QResizeEvent>
#include <QDebug>

ScrollingMessageDisplayWidget::ScrollingMessageDisplayWidget(QWidget *parent, int speed)
    : QWidget(parent),
      count(0),
      showSpeed(speed)
{
    showLabel = new QLabel(this);
    connect(&timer,SIGNAL(timeout()),this,SLOT(updataPosition()));
    setAutoFillBackground(true);
    QPalette palette;
    palette.setColor(backgroundRole(), Qt::cyan);
    setPalette(palette);

}

ScrollingMessageDisplayWidget::~ScrollingMessageDisplayWidget()
{
    
}
void ScrollingMessageDisplayWidget::resizeEvent(QResizeEvent *e)
{
    if (e->oldSize() != size()) {
        initUI();
    }
}
void ScrollingMessageDisplayWidget::initUI()
{
    displayHeigth = height();
    displayWidth = width();
    showMessageSecond = (1.0*(displayWidth+MessageLength) / showSpeed)*10+5;
}
void ScrollingMessageDisplayWidget::setMessage(const QString &message)
{
    m_queue.append(message);
    if (timer.isActive()) {
    } else {
        doShow();//这边和
    }

}
void ScrollingMessageDisplayWidget::showEnd()
{
    if (count == showMessageSecond) {
        timer.stop();
        count = 0;
        doShow();//这边可能存在问题
    }
}
void ScrollingMessageDisplayWidget::updataPosition()
{
    showLabel->move(displayWidth - 0.1*count*showSpeed,0);
    ++count;
    showEnd();

}
void ScrollingMessageDisplayWidget::doShow()
{
    if (!m_queue.isEmpty()) {
        showMessage = m_queue.first();
        m_queue.removeFirst();
        QFont font("Times", displayHeigth/2, QFont::Bold);
        QFontMetrics fm(font);
        MessageLength = fm.width(showMessage);
        showLabel->setFont(font);
        showLabel->setText(showMessage);
        showLabel->setGeometry(displayWidth,0,MessageLength,displayHeigth);
        showMessageSecond = (1.0 * (displayWidth+MessageLength) / showSpeed) * 10 + 5;
        timer.start(100);
    }


}
